import axios, { AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/user'
import { useRouter } from 'vue-router';
let baseURL = window.PLATFROM_CONFIG.baseUrl

let token_status = true

if (window.location.hostname == 'localhost') {
  baseURL = ''
}

const service = axios.create({
  baseURL: baseURL,
  timeout: 120000,
  withCredentials: true,
})

// 请求拦截器
service.interceptors.request.use(config => {
  let { token } = useUserStore()
  if (token) {
    config.headers['token'] = token;
  }
  return config
}, error => {
  console.log('request error ===', error)
  throw Error(error)
})

// 返回拦截器
service.interceptors.response.use(
  response => {
    if (response.status != 200 || response.data.state != 200) {
      if (response.state == 98 || response.data.state == 98) {
        if (token_status) {
          token_status = false
          let userStore = useUserStore()
          let router = useRouter()
          userStore.logout().then(() => {
            router.push(`/login`)
          })
        }
        return response.data
      }
      if(response.config.url !=='/management/earth.country/getStatesList' && response.config.url !=='/management/machine.machine_error_code/getTypeList'){
        // 返回错误处理
        ElMessage({
          message: response.data.msg || 'request error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(response.data)
    }
    token_status = true
    return response.data
  },
  error => {
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export interface Response<T> {
  state: number,
  code: number,
  data: T,
  msg: string
}

const request = <T>(options: AxiosRequestConfig) => {
  return service<Response<T>, Response<T>>(options)
}

export default request
